# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError
from odoo import modules
from json2table import convert
from urllib.parse import urljoin
from datetime import datetime
import logging
import os

import traceback
import re

_logger = logging.getLogger(__name__)

# JSON转换HTML样式
build_direction = "LEFT_TO_RIGHT"
table_attributes = {"style" : "width:100%", "class" : "table table-striped"}


class OcrProxy(models.Model):
    _name = 'ocr.proxy'
    _description = 'Ocr Proxy'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _order = 'create_date desc'

    # email相关字段
    doc_id = fields.Char(string='文档识别标识', tracking=True)

    email_id = fields.Many2one('email.proxy', tracking=True)

    state = fields.Selection([
        ('ocr_recognition', '识别成功'),
        ('ocr_recognition_error', '识别异常'),
    ], string='识别结果', tracking=True)
    remark = fields.Text('识别异常文本', tracking=True)

    ocr_recognition_type = fields.Selection([
        ('pdf', 'PDF文件识别'),
        ('image', '图片文件识别'),
        ('all', '全部识别'),
    ], string='识别类型', tracking=True, default='all')


    json_source_data = fields.Text('OCR解析JSON源数据')
    json_source_data_table = fields.Html('', compute='_compute_json_source_data_table')

    choose_ocr = fields.Boolean('选择识别', default=True)

    reference_order_ids = fields.One2many('order.model', 'ocr_id', string='Reference order')

    order_create_result = fields.Boolean('订单创建结果', default=True)

    @api.depends('json_source_data')
    def _compute_json_source_data_table(self):
        for rec in self:
            if rec.json_source_data:
                html = convert(eval(rec.json_source_data), build_direction=build_direction, table_attributes=table_attributes)
                rec.json_source_data_table =html
            else:
                rec.json_source_data_table = False

    def open_ocr_result(self):
        ...

    def ocr_recognition(self):
        from veryfi import Client
        file_path, document_json_list = None, []
        # get your keys here: https://hub.veryfi.com/api/
        client_id = 'vrfGyKZoRm7YgCOtbYS3tX1XlkdgTBgvma09Pes'
        client_secret = '1UvN9oBiUGPRNO7kr5IPGEaJMDNYV9WFTKvJ0CIcizumAAhjx6fNKNmAZrV9xu8XZLSFPVeOhSZ3oBINk5uulytmNI02kYi5pjbns3btbEV14VuL1f4PjWd5Vt3nLwxL'
        username = 'lifufu188'
        api_key = '86aa439f816ad2ec006fdafa0a8f7d4f'

        veryfi_client = Client(client_id, client_secret, username, api_key)

        categories = ['Grocery', 'Utilities', 'Travel']
        email_id = self.env.context.get('active_id')
        files = self.env['email.proxy'].browse([email_id]).email_attachment_ids
        # 获取模块的路径
        module_path = modules.get_module_resource('oa_system')

        # 基于模块的路径构建文件的完整路径
        for file in files:
            file_path = os.path.join(module_path, 'tmp_upload_attachment', 'attachments', file.name)
            with open(file_path, 'wb') as f:
                f.write(file.raw)
            if file_path:
            # This submits document for processing (takes 3-5 seconds to get response)
                document_json = veryfi_client.process_document(file_path, categories=categories)
                document_json_list.append(document_json)
        return document_json_list

    def parse_document_json(self, document_json_list):
        email_id = self.env.context.get('active_id')

        create_list = [{
            'doc_id':i.get('id'),
            'email_id':email_id,
            'ocr_recognition_type':self.ocr_recognition_type,
            'state':'ocr_recognition',
            'json_source_data':i,
        }
            for i in document_json_list
        ]

        return create_list


    def create_ocr_proxy_record(self, create_list):
        self.create(create_list)

    def check_ocr_condition(self):
        if not self.ocr_recognition_type:
            raise ValidationError("请先选择OCR识别类型")
    def confirm_ocr(self):
        self.check_ocr_condition()
        email_id = self.env.context.get('active_id')
        email_obj = self.env['email.proxy'].sudo().browse([email_id])
        try:
            document_json_list = self.ocr_recognition()
            if len(document_json_list):
                self.env.cr.commit()
                email_obj.state = 'ocr_recognition_success'
                create_list = self.parse_document_json(document_json_list)
                self.create_ocr_proxy_record(create_list)
            else:
                self.state = 'ocr_recognition_fail'
        except Exception as e:
            email_obj.state = 'system_error'
            _logger.error(traceback.format_exc())
            return {
                "type": "ir.actions.client",
                "tag": "display_notification",
                "params": {
                    "title": _("Error"),
                    "type": "danger",
                    "message": _(f"系统异常{e}"),
                    "sticky": False,
                    'next': {'type': 'ir.actions.act_window_close'}
                },
            }












